package org.example.juc.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 该示例用于演示ThreadLocal在线程池场景下的数据污染问题
 */
public class ThreadLocalExample {
    // 定义一个 ThreadLocal 变量
    private static ThreadLocal<String> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        // 创建一个固定大小的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        // 提交第一个任务
        executorService.submit(() -> {
            threadLocal.set("Task 1");
            System.out.println(Thread.currentThread().getName() + " - " + threadLocal.get());
            // 模拟任务执行时间
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 提交第二个任务
        executorService.submit(() -> {
            threadLocal.set("Task 2");
            System.out.println(Thread.currentThread().getName() + " - " + threadLocal.get());
            // 模拟任务执行时间
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 提交第三个任务，检查是否有数据污染
        executorService.submit(() -> {
            System.out.println(Thread.currentThread().getName() + " - " + threadLocal.get());
            // 清理 ThreadLocal 变量
            threadLocal.remove();
        });

        // 关闭线程池
        executorService.shutdown();
    }
}